#include <wx/wx.h>
#include <wx/cmdline.h>
#include <wx/filename.h>

#include "bgl2txt.h"
#include "bglfile.h"
#include "bglreader.h"
#include "txtbuilder.h"
#include "verinfo.h"

IMPLEMENT_APP_CONSOLE( Bgl2TxtConsole )

void Bgl2TxtConsole::convert() {
    wxFileName ungzfn(bglfile);
    
    ungzfn.SetExt(_T("txt"));
    
    DictBuilder *builder = new TxtBuilder(ungzfn.GetFullPath());
    DictReader *reader = new BGLReader( bglfile, builder, source_charset, target_charset);
    
    if (!reader->convert() ) {
        wxPrintf(_T("Error converting %s\n"), bglfile.c_str());
        return;
    }
    
    builder->finish();
}

void Bgl2TxtConsole::OnInitCmdLine(wxCmdLineParser& parser) {
    parser.SetSwitchChars(_T("-"));
    
    wxString logo = _T("bgl2txt ");
    logo = logo + _T(PRODUCT_VERSION_NUMBER "\n" PRODUCT_COPYRIGHT "\n");
    parser.SetLogo(logo);
    
    parser.AddParam(_T("<.bgl file>"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_MANDATORY);
    parser.AddOption(_T("s"), wxEmptyString, _T("source charset"), wxCMD_LINE_VAL_STRING);
    parser.AddOption(_T("t"), wxEmptyString, _T("target charset"), wxCMD_LINE_VAL_STRING);
    return wxAppConsole::OnInitCmdLine(parser);
}

bool Bgl2TxtConsole::OnCmdLineParsed(wxCmdLineParser& parser) {
    bglfile = parser.GetParam();
    parser.Found(_T("s"), &source_charset);
    parser.Found(_T("t"), &target_charset);
    
    return wxAppConsole::OnCmdLineParsed(parser);
}

int Bgl2TxtConsole::OnRun() {
    convert();
    return 0;
}
